package com.jy.chat.kit.utils

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.request.RequestOptions
import com.jy.chat.kit.GlideKitImageEngine
import com.jy.chat.kit.IMCenter
import com.jy.chat.kit.RongIM
import com.jy.chat.kit.config.ConversationClickListener
import com.jy.chat.kit.config.ConversationListBehaviorListener
import com.jy.chat.kit.config.RongConfigCenter
import com.jy.chat.kit.conversation.extension.RongExtensionManager
import com.jy.chat.kit.conversationlist.model.BaseUiConversation
import com.jy.chat.kit.manager.MyExtensionConfig
import com.jy.chat.sight.SightExtensionModule
import com.jy.horny.function.MainActivity
import com.jy.horny.function.info.ProfileActivity
import io.rong.imlib.IRongCoreCallback
import io.rong.imlib.IRongCoreEnum
import io.rong.imlib.IRongCoreEnum.CoreErrorCode
import io.rong.imlib.RongCoreClient
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import io.rong.imlib.model.Message
import io.rong.imlib.model.UserInfo


object RongConfigUtil {
    fun updatePortrait() {
        IMCenter.setConversationClickListener(object : ConversationClickListener {
            override fun onUserTitleClick(
                context: Context?,
                conversationType: Conversation.ConversationType?,
                targetId: String?
            ): Boolean {
//                if(targetId.equals(BaseConfig.getInstance.getString(SpName.serverUserCode,""))){
//                    return true
//                }
//                val intent = Intent(context, ProfileActivity::class.java)
//                intent.putExtra("isIM", true)
//                intent.putExtra("userCodeFriend", targetId)
//                context?.startActivity(intent)
                return true
            }

            override fun onUserPortraitClick(
                context: Context?,
                imageView: ImageView?,
                conversationType: Conversation.ConversationType?,
                user: UserInfo?,
                targetId: String?
            ): Boolean {
                if (user?.userId != targetId) {
                    return true
                }
//                if (targetId == BaseConfig.getInstance.getString(SpName.serverUserCode,"")){
//                    return true
//                }
//                if(SDActivityManager.instance.isEmpty){
//                    return true
//                }
//                FirebaseEventUtils.logEvent(FirebaseEventTag.Chat_Avatar.name)
                val intent = Intent(context, ProfileActivity::class.java)
                intent.putExtra("isIM", true)
                intent.putExtra("userCodeFriend", targetId)
                context?.startActivity(intent)
                return true
            }

            override fun onUserPortraitLongClick(
                context: Context?,
                conversationType: Conversation.ConversationType?,
                user: UserInfo?,
                targetId: String?
            ): Boolean {

                return false
            }

            override fun onMessageClick(
                context: Context?,
                view: View?,
                message: Message?
            ): Boolean {
                return false
            }

            override fun onMessageLongClick(
                context: Context?,
                view: View?,
                message: Message?
            ): Boolean {
                return true
            }

            override fun onMessageLinkClick(
                context: Context?,
                link: String?,
                message: Message?
            ): Boolean {
                return false
            }

            override fun onReadReceiptStateClick(context: Context?, message: Message?): Boolean {
                return false
            }

        })

        RongIM.getInstance().setMessageAttachedUserInfo(true)

        RongIM.setConversationListBehaviorListener(object : ConversationListBehaviorListener {
            override fun onConversationPortraitClick(
                context: Context?,
                imageView: ImageView?,
                portraitUrl: String?,
                conversationType: Conversation.ConversationType?,
                targetId: String?
            ): Boolean {
                return false
            }

            override fun onConversationPortraitLongClick(
                context: Context?,
                conversationType: Conversation.ConversationType?,
                targetId: String?
            ): Boolean {
                return false
            }

            override fun onConversationLongClick(
                context: Context?,
                view: View?,
                conversation: BaseUiConversation?
            ): Boolean {
                return true
            }

            override fun onConversationClick(
                context: Context?,
                view: View?,
                conversation: BaseUiConversation?
            ): Boolean {
//                if (conversation?.mCore?.targetId.equals(BaseConfig.getInstance.getString(SpName.serverUserCode,""))) {
//                    FirebaseEventUtils.logEvent(FirebaseEventTag.IM_Notification.name)
//                }else {
//                    FirebaseEventUtils.logEvent(FirebaseEventTag.IM_Chat.name)
//                }
                return false
            }

        })

    }

    fun getUnreadConversationList(): List<Conversation?> {
        var conversation = listOf<Conversation?>()
        RongCoreClient.getInstance().getUnreadConversationList(object :
            IRongCoreCallback.ResultCallback<List<Conversation?>?>() {
            override fun onSuccess(conversations: List<Conversation?>?) {
                conversation = conversations!!
                // 成功并返回会话信息
            }

            override fun onError(e: IRongCoreEnum.CoreErrorCode) {}
        }, Conversation.ConversationType.PRIVATE)
        return conversation

    }

    fun configurationRong() {
        updatePortrait()
        RongExtensionManager.getInstance().registerExtensionModule(SightExtensionModule())
        RongExtensionManager.getInstance().extensionConfig = MyExtensionConfig()

    }

    fun connectIM(token: String, activity: Activity) {
        RongIM.connect(token, object : RongIMClient.ConnectCallback() {
            override fun onSuccess(code: String) {
            }

            override fun onError(errorCode: RongIMClient.ConnectionErrorCode) {
                Log.e("~~~", "onError: $errorCode")
//                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
//                    override fun addBody(requestBody: OkHttpBodyEntity) {
//                        requestBody.setPost(Constant.im_token_Url)
//                    }
//                }, object : SDOkHttpResoutCallBack<IMTokenGetEntity>() {
//                    override fun onSuccess(entity: IMTokenGetEntity) {
//                        connectIM(entity.data.token,activity)
//                    }
//
//                    override fun onFailure(code: Int, msg: String) {
//                    }
//                })
            }

            override fun onDatabaseOpened(code: RongIMClient.DatabaseOpenStatus) {
            }
        })
    }

    fun deleteRongUserHistory(targetId: String) {
        RongIMClient.getInstance()
            .removeConversation(Conversation.ConversationType.PRIVATE,
                targetId, object : RongIMClient.ResultCallback<Boolean?>() {
                    override fun onSuccess(success: Boolean?) {}
                    override fun onError(errorCode: RongIMClient.ErrorCode?) {}
                })
        RongCoreClient.getInstance().deleteMessages(
            Conversation.ConversationType.PRIVATE,
            targetId,
            object : IRongCoreCallback.ResultCallback<Boolean?>() {
                /**
                 * 删除消息成功回调
                 */
                override fun onSuccess(bool: Boolean?) {
                }

                /**
                 * 删除消息失败回调
                 * @param errorCode 错误码
                 */
                override fun onError(coreErrorCode: IRongCoreEnum.CoreErrorCode) {}
            })

        val recordTime: Long = System.currentTimeMillis()
        val cleanRemote = true // 同时从服务端删除对应的消息历史记录


        RongCoreClient.getInstance()
            .cleanHistoryMessages(Conversation.ConversationType.PRIVATE,
                targetId, recordTime, cleanRemote,
                object : IRongCoreCallback.OperationCallback() {
                    /**
                     * 删除消息成功回调
                     */
                    override fun onSuccess() {
                    }

                    /**
                     * 删除消息失败回调
                     * @param errorCode 错误码
                     */
                    override fun onError(coreErrorCode: CoreErrorCode) {}
                })
    }

}